'use strict';

const {Controller} = require('egg');
const fs = require('mz/fs');
const path = require('path');
const http = require('http')

module.exports = class extends Controller {
  async upload() {
    const {ctx} = this;
    try {
      ctx.body = {files: {file: 'http://' + ctx.host + '/' + ctx.request.files[0].filepath}}
    } catch (err) {
      ctx.logger.error(err);
    } finally {
      // 需要删除临时文件
      // await fs.unlink(file.filepath);
    }
  }

  async cleanFile() {
    const {app, ctx} = this;
    try {
      // await this.del(process.cwd() + '/' + app.config.multipart.tmpdir + '/')
      await this.del(app.baseDir + '/' + app.config.multipart.tmpdir + '/')
      ctx.body = {message: '删除成功'}
    } catch (e) {
      ctx.body = {message: '删除失败'}
    }
  }

  del(dirpath) {
    if (fs.existsSync(dirpath)) {
      let fileList = fs.readdirSync(dirpath);
      fileList.forEach(x => {
        let p = path.resolve(dirpath, x);
        let pinfo = fs.statSync(p);
        if (pinfo.isFile()) {
          fs.unlinkSync(p);
        } else if (pinfo.isDirectory()) {
          this.del(p);
        }
      });
      fs.rmdirSync(dirpath);
    }
  }

  async open() {
    const {app, ctx} = this;

    console.log(11, app.baseDir)
    fs.readFile('/Users/liubao/WebstormProjects/egg-backend/upload/admin-system/2020/07/23/17/5a1b5456-6415-44aa-b89c-b49c1edde142.GIF', 'binary', function (err, file) {
      if (err) {
        console.log(err);
        return;
      } else {
        http.createServer(function (req, res) {
          res.writeHead(200, {'Content-Type': 'image/jpeg'});
          res.write(file, 'binary');
          res.end();
          return;
        }).listen(8888);
      }
    });
  }
};
